#!/usr/bin/env python
# encoding: utf-8
'''
@author: 王震
@license: 四川凡狼科技有限公司
@contact: 2668985108@qq.com
@file: sqlMethods.py
@time: 2021/10/2 9:59 上午
@desc:
'''
import json
import itsdangerous
from flask_httpauth import HTTPTokenAuth
from flask import request
from app.model.user.user import User
from app.msg.resp import response_json
from app.msg.tips import tips, tipsText
from app.serialize.user import UserObj
from contextlib import contextmanager
from main import db

salt = 'sdaf'
t = itsdangerous.TimedJSONWebSignatureSerializer(salt, expires_in=36000)  # 过期时间600秒
auto = HTTPTokenAuth(scheme='Token')


def get_obj(name, class_obj):
    return class_obj.query.filter_by(name=name).count()


def existence(obj, target):
    obj = obj
    target = target
    #  将json类型转化为字典类型
    if type(obj) != dict:
        obj = json.loads(obj)
    if type(target) != dict:
        target = json.loads(target)
    for key in target:
        if not (key in obj):
            return True


def set_content_type():
    headers = request.headers
    if headers['Content-Type'] != 'application/json':
        return True


def create_token(obj):
    user_obj = UserObj()
    data = user_obj.dump(obj)
    res = t.dumps(data)
    token = res.decode()
    return token


@auto.verify_token
def verify_token(token):
    try:
        token = request.headers['token']
        res = t.loads(token)
        user = User.query.get(res['id'])
        if user:
            return True
    except:
        return False


@auto.error_handler
def error_handler():
    return response_json(code=tips['logged'], msg=tipsText['logged'])


@contextmanager
def auto_commit_db():
    try:
        yield
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        return e
